$(function() {
    var appModel = Backbone.Model.extend({
        urlRoot : function() {
            if(debug) {
                return "interface.json";
            } else {
                return interfaceRoot + "/api/apps";
            }
        },
        defaults : function() {
            return {
                order : myApps.nextOrder(),
                name : "name",
                description : "description",
                platform : "platform",
                appUrl : "appUrl",
                admin : "admin",
                adminContact : "adminContact"
            };
        },
        initialize : function() {
            for(var key in this.defaults()) {
                if(key == "order")
                    continue;
                if(!this.get(key)) {
                    this.set({
                        key : this.defaults().key
                    });
                }
            }
        },
        parse : function(data) {//fetch,save 触发
            if(data.insertId) {
                data.id = data.insertId;
            }

            console.log(data);
            return data;
        }
    });

    var appList = Backbone.Collection.extend({

        model : appModel,

        url : function() {
            if(debug) {
                return "getApps.json";
            } else {
                return interfaceRoot + "/api/apps";
            }
        },
        nextOrder : function() {
            if(!this.length)
                return 1;
            return this.last().get('order') + 1;
        },
        parse : function(data) {
            // 'data' contains the raw JSON object
            console.log(data);
            return data;
        },
        count : function() {
            return this.length;
        },
        comparator : function(app) {
            return app.get('order');
        }
    });

    var trView = Backbone.View.extend({
        tagName : "tr",

        template : _.template($('#appTable_tr_template').html()),

        events : {
            "click .manageAds" : "manageAds",
            "click .delete" : "confirmDelete",
        },

        initialize : function() {
            this.listenTo(this.model, 'change', this.render);
            this.listenTo(this.model, 'destroy', this.remove);
        },

        render : function() {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        },

        manageAds : function() {
            //click .manageAds button
            //TO DO
            var id = this.model.get("id");
            var name = this.model.get("name");
            var platform = this.model.get("platform");
            var url = "manageAds.html?id=" + id + "&name=" + name + "&platform=" + platform;
            window.location = window.encodeURI(url);
        },

        confirmDelete : function() {
            //click .delete button
            //TO DO
            var model = this.model;
            $("#deleteConfirmModal").modal();
            $("#deleteConfirmModal .btn-primary").unbind();
            $("#deleteConfirmModal .btn-primary").click(function() {
                model.destroy({
                    success : function(model, response) {

                    },
                    error : function(model, response) {
                        myApps.add(model)//删除失败
                        alert("删除失败")
                    }
                });
                $("#deleteConfirmModal").modal("hide");
            })
        }
    });

    var appView = Backbone.View.extend({
        el : $("#container"),

        template : _.template($('#stats-template').html()),

        events : {
            "click #addAppButton" : "addAppModal",
            "click #addAppModal .modal-footer .btn-primary" : "addApp"
        },

        initialize : function() {
            this.listenTo(myApps, 'add', this.addOne);
            this.listenTo(myApps, 'reset', this.addAll);
            this.listenTo(myApps, 'all', this.render);

            myApps.fetch();
        },

        render : function() {
            var count = myApps.count();

            this.$("#stats").html($.trim(this.template({
                count : count
            })));

        },
        addAppModal : function() {
            $('#addAppModal').modal()
        },

        addApp : function() {
            var $modal = $('#addAppModal');
            var name = $modal.find("input[name=name]").val();
            var description = $modal.find("textarea").val();
            var platform = $modal.find("input[name=platform]:checked").val();
            var appUrl = $modal.find("input[name=appUrl]").val();
            var admin = $modal.find("input[name=admin]").val();
            var adminContact = $modal.find("input[name=adminContact]").val();

            if(name && platform && appUrl && admin && adminContact) {
                var myApp = new appModel({
                    name : name,
                    description : description,
                    platform : platform,
                    appUrl : appUrl,
                    admin : admin,
                    adminContact : adminContact
                });

                myApp.save({
                    name : name,
                    description : description,
                    platform : platform,
                    appUrl : appUrl,
                    admin : admin,
                    adminContact : adminContact
                }, {
                    success : function(model, response) {
                        myApps.add(myApp);

                        $('#addAppModal').modal('hide');
                        //清空表单
                        $modal.find("input:not([name=platform])").val("");
                        $modal.find("textarea").val("");
                    },
                    error : function(model, response) {
                        alert("保存失败");
                    }
                });

            }
        },

        addOne : function(app) {
            var view = new trView({
                model : app
            });
            this.$("#appTable tbody").append(view.render().el);
        },
        addAll : function() {
            myApps.each(this.addOne, this);
        }
    });

    var myApps = new appList;
    var myAppView = new appView;

    $("#button2").click(function() {
        console.log(JSON.stringify(myApps.toJSON()))
    })
})

